import Vue from 'vue'
import Vuex from 'vuex'
import createPersistedState from "vuex-persistedstate";

Vue.use(Vuex)

export default new Vuex.Store({
  plugins: [createPersistedState()],
  state: {
    todos: JSON.parse(localStorage.getItem("vuex") || '[]'),
    activeTab: "all"
  },
  getters: {
    activeTab: function (state) {
      return state.activeTab;
    },
    remaining: function (state) {
      let remainingTodos = state.todos.filter(v => {
        // return !v.stasue//false=>返回
        if (!v.status) {
          return true;
        }
      })
      return remainingTodos.length;
    },
    allChecked: function (state) {
      let checked = true;
      //只要todo里面有一个status false=>allchecked =false;
      state.todos.map((v) => {
        if (!v.status) checked = false;
      });
      return checked;
    },
    filterTodos: function (state) {
      if (state.activeTab === "all") {
        return state.todos;
      } else if (state.activeTab === "active") {
        return state.todos.filter(v => {
          return !v.status;
        })
      } else if (state.activeTab === "completed") {
        return state.todos.filter(v => {
          return v.status;
        })
      }
    },
  },
  mutations: {
    handleClearCompleted: function (state) {
      let activeTodos = state.todos.filter((v) => {
        return !v.status;
      });
      state.todos = activeTodos;

    },
    changeActiveTab: function (state, { payload }) {
      state.activeTab = payload.activeTab;
    },

    deletTodo: function (state, { payload }) {
      state.todos.splice(payload.index, 1)
    },
    addTodo: function (state, { payload }) {
      state.todos.push(payload);
    },
    allCheck: function (state) {
      // console.log(state.todos);
      // let newTodos = JSON.parse(JSON.stringify(state.todos));
      state.todos.map((v) => {
        v.status = true;
      });
    }
  },
  actions: {
  },
  modules: {
  }
})
